package com.feng.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.feng.common.constant.AuthServerConstant;
import com.feng.common.exception.BizCodeEnume;
import com.feng.common.utils.HttpUtils;
import com.feng.common.utils.R;
import com.feng.common.vo.MemberEntity;
import com.feng.gulimall.auth.feign.MemberFeignService;
import com.feng.gulimall.auth.feign.ThirdPartFeignService;
import com.feng.gulimall.auth.utils.RandomUtil;
import com.feng.gulimall.auth.vo.UserLoginVo;
import com.feng.gulimall.auth.vo.UserRegisterVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {
//    @GetMapping("/login.html")
//    public String loginPage(){
//         return "login";
//    }
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ThirdPartFeignService thirdPartFeignService;
    @Autowired
    private MemberFeignService memberFeignService;
    @ResponseBody
    @GetMapping("/sms/sendCode")
     public R sendCode(@RequestParam("phone") String phone){
        //验证码防刷
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if(!StringUtils.isEmpty(redisCode)){
            long l = Long.parseLong(redisCode.split("_")[1]);
            if(System.currentTimeMillis()-l<60000){
              //60s不能再发
                return R.error(BizCodeEnume.VAILD_SMS_CODE_EXCEPTON.getCode(),BizCodeEnume.VAILD_SMS_CODE_EXCEPTON.getMsg());
            }
        }

        String code = RandomUtil.getFourBitRandom();
        //redis缓存验证码，防止同一个手机号在60m内在此发送验证码
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,code+"_"+System.currentTimeMillis(),5, TimeUnit.MINUTES);
        thirdPartFeignService.sendCode(phone,code);
         return R.ok();
     }
    @GetMapping(value = "/login.html")
    public String loginPage(HttpSession session) {

        //从session先取出来用户的信息，判断用户是否已经登录过了
        Object attribute = session.getAttribute("loginUser");
        //如果用户没登录那就跳转到登录页面
        if (attribute == null) {
            return "login";
        } else {
            return "redirect:http://gulimall.com";
        }

    }
     @PostMapping("/register")
     public String regist(@Valid UserRegisterVo vo, BindingResult result, RedirectAttributes redirectAttributes){
        if(result.hasErrors()){

            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(fieldError -> {
                return fieldError.getField();
            }, fieldError -> {
                return fieldError.getDefaultMessage();
            }));
            redirectAttributes.addFlashAttribute("errors",errors);
            //校验出错，转发到注册页
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        //校验验证码
         String code = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
         //真正注册调用远程服务进行注册
         if(!StringUtils.isEmpty(code)){
             if(code.split("_")[0].equals(vo.getCode())){
                  //验证码校验成功删除验证码
                 stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                 //调用远程服务
                 R r = memberFeignService.register(vo);
                 if(r.getCode()==0){
                     //成功

                     return "redirect:http://auth.gulimall.com/login.html";
                 }else {
                     Map<String,String> errors=new HashMap<>();
                     errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
                     redirectAttributes.addFlashAttribute("error");
                     return "redirect:http://auth.gulimall.com/reg.html";
                 }
             }
             else{
                 Map<String,String> errors=new HashMap<>();
                 errors.put("code","验证码错误");
                 //校验出错，转发到注册页
                 redirectAttributes.addFlashAttribute("errors",errors);
                 return "redirect:http://auth.gulimall.com/reg.html";
             }

         }
         else {
             Map<String,String> errors=new HashMap<>();
             errors.put("code","验证码错误");
             //校验出错，转发到注册页
             redirectAttributes.addFlashAttribute("errors",errors);
             return "redirect:http://auth.gulimall.com/reg.html";
         }



     }
     @PostMapping("/login")
     public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){
        //远程登录
         R login = memberFeignService.login(vo);
         if(login.getCode()==0){
             //成功
             MemberEntity data = login.getData("data",new TypeReference<MemberEntity>(){});
             session.setAttribute("loginUser",data);
             return "redirect:http://gulimall.com";
         }
         else {
             Map<String,String> errors=new HashMap<>();
             errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
             //校验出错，转发到注册页
             redirectAttributes.addFlashAttribute("errors",errors);
             return "redirect:http://auth.gulimall.com/login.html";
         }

     }

}
